package cn.myspringboot.articletype.service.impl;

import cn.myspringboot.anno.Logs;
import cn.myspringboot.articletype.mapper.ArticleTypeMapper;
import cn.myspringboot.articletype.service.ArticleTypeService;
import cn.myspringboot.user.domain.ArticleType;
import cn.myspringboot.user.domain.vo.ArticleTypeVo;
import cn.myspringboot.user.query.ArticleTypeQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ArticleTypeServiceImpl implements ArticleTypeService {
    @Autowired
    private ArticleTypeMapper articleTypeMapper;

    @Override
    @Logs
    public void insert(ArticleType articleType) {
        articleTypeMapper.insert(articleType);
    }

    @Override
    public List<ArticleType> findAll() {
        return articleTypeMapper.findAll();
    }

    @Override
    public ArticleType findById(Long id) {
        return articleTypeMapper.findById(id);
    }

    @Override
    @Logs
    public void update(ArticleType articleType) {
        articleTypeMapper.update(articleType);
    }

    @Override
    @Logs
    public void delete(Long id) {
        articleTypeMapper.delete(id);
    }

    @Override
    public List<ArticleType> getArticleTypeByPage(ArticleTypeQuery query) {
        return articleTypeMapper.getArticleTypeByPage(query);
    }

    @Override
    @Logs
    public void batchdelete(List<Long> ids) {
        articleTypeMapper.batchdelete(ids);
    }

    @Override
    public List<ArticleTypeVo> articleTypeTree() {
        //原始数据
        List<ArticleType> all = articleTypeMapper.findAll();
        //将原始数据返回类型ArticleType改为ArticleTypeVo
        List<ArticleTypeVo> voList = all.stream().map(a -> {
            ArticleTypeVo vo = new ArticleTypeVo();
            vo.setValue(a.getId());
            vo.setParentId(a.getParentId());
            vo.setLabel(a.getTypeName());
            return vo;
        }).collect(Collectors.toList());
        //将value作为key 将articleTypeVo作为值
        Map<Long,ArticleTypeVo> articleTypeVoMap = new HashMap<>();
        for (ArticleTypeVo articleTypeVo : voList) {
            articleTypeVoMap.put(articleTypeVo.getValue(), articleTypeVo);
        }
        //准备存储的返回数据
        List<ArticleTypeVo> list = new ArrayList<>();
        //多层级处理
        for (ArticleTypeVo articleTypeVo : voList) {
            if(articleTypeVo.getParentId() == null){
                list.add(articleTypeVo);
            }else {
                //通过上级id去找上级
                ArticleTypeVo typeVo = articleTypeVoMap.get(articleTypeVo.getParentId());
                //找到过后将自己的数据放在上级中
                typeVo.getChildren().add(articleTypeVo);
            }
        }
        return list;
    }
}
